package com.lun.blog.controller.admin;

import com.lun.blog.pojo.Picture;
import com.lun.blog.pojo.Type;
import com.lun.blog.service.PictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/admin")
public class PictureController {

    @Autowired
    private PictureService pictureService;

    @GetMapping("/findPicture")
    public String findPicture(@PageableDefault(size = 5,sort = {"id"},direction = Sort.Direction.DESC) Pageable pageable,
                              Model model){
        model.addAttribute("page",pictureService.listPage(pageable));
        return "admin/pictures";
    }
    @GetMapping("/picture/add")
    public String addPicture(){
        return "admin/pictures-input";
    }

    @PostMapping("/picture/savePicture")
    public String savePicture(Picture picture, RedirectAttributes redirectAttributes){
        Picture byPictureName = pictureService.findByPictureName(picture.getPictureName());
        if(byPictureName==null){
            pictureService.savePicture(picture);
            redirectAttributes.addFlashAttribute("message","保存"+picture.getPictureName()+"成功");
        }else {
            redirectAttributes.addFlashAttribute("message","图片已存在，请重新上传");
        }
        return "redirect:/admin/findPicture";
    }

    @RequestMapping ("/picture/deletePicture")
    public String deletePicture(String id,RedirectAttributes attributes){
        pictureService.deletePicture(Long.parseLong(id));
        attributes.addFlashAttribute("message","删除图片成功");
        return "redirect:/admin/findPicture";
    }
    @RequestMapping("/picture/updatePicture")
    public String updatePicture(String id,Model model){
        Picture picture = pictureService.getPicture(Long.parseLong(id));
        model.addAttribute("picture",picture);
        return "admin/pictures-update";
    }
    @PostMapping("/updatePicture")
    public String updatePicture(Picture picture,RedirectAttributes attributes){
        pictureService.savePicture(picture);
        attributes.addFlashAttribute("message","修改"+picture.getPictureName()+"成功");
        return "redirect:/admin/findPicture";
    }

}
